﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MockBusiness;
using MockDataTransferObject;
using MockCommon;
using System.Globalization;
namespace Presentation
{
    public partial class ListTimesheet : System.Web.UI.Page
    {
        private TimesheetBusiness _timesheetBusiness;
        private TimesheetStatusBusiness _timesheetstatusBusiness;
        private ContractBusiness _contractBusiness;
        private ReasonBusiness _reasonBusiness;
        private Label _warningLabel;
        private Label _errorLabel;
        private Label _successLabel;
        private DropDownList _statusDropDownList;
        private ListView _timesheetListView;
        private CheckBox _allSearchCheckBox;
        private TextBox _fromDateTextBox;
        private TextBox _toDateTextBox;
        private Button _filterButton;

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                _timesheetBusiness = TimesheetBusiness.RetrieveInstance();
                _timesheetstatusBusiness = TimesheetStatusBusiness.RetrieveInstance();
                _contractBusiness = ContractBusiness.RetrieveInstance();
                _reasonBusiness = ReasonBusiness.RetrieveInstance();
                _warningLabel = (Label)Master.FindControl("WarningLabel");
                _errorLabel = (Label)Master.FindControl("ErrorLabel");
                _successLabel = (Label)Master.FindControl("SuccessLabel");
                _statusDropDownList = (DropDownList)ListTimesheetUserControl.FindControl("StatusDropDownList");
                _timesheetListView = (ListView)ListTimesheetUserControl.FindControl("TimesheetListView");
                _allSearchCheckBox = (CheckBox)ListTimesheetUserControl.FindControl("AllSearchCheckBox");
                _fromDateTextBox = (TextBox)ListTimesheetUserControl.FindControl("FromDateTextBox");
                _toDateTextBox = (TextBox)ListTimesheetUserControl.FindControl("ToDateTextBox");
                _filterButton = (Button)ListTimesheetUserControl.FindControl("FilterButton");
                _statusDropDownList.SelectedIndexChanged += new EventHandler(StatusDropDownList_SelectedIndexChanged);
                _allSearchCheckBox.CheckedChanged += new EventHandler(AllSearchCheckBox_CheckedChanged);
                _filterButton.Click += new EventHandler(FilterButton_Click);
                _timesheetListView.ItemUpdating += new EventHandler<ListViewUpdateEventArgs>(TimesheetListView_ItemUpdating);
                _timesheetListView.ItemDeleting += new EventHandler<ListViewDeleteEventArgs>(TimesheetListView_ItemDeleting);
                _timesheetListView.ItemCanceling += new EventHandler<ListViewCancelEventArgs>(TimesheetListView_ItemCanceling);
                _timesheetListView.ItemEditing += new EventHandler<ListViewEditEventArgs>(TimesheetListView_ItemEditing);
                _timesheetListView.DataBound += new EventHandler(TimesheetListView_DataBound);
            }
            catch (MockException exception)
            {
                Application["error"] = exception;
                Response.Redirect("Error.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["user"] == null)
            {
                Response.Redirect("LogOn.aspx");
            }
            else
            {
                User user = (User)Session["user"];
                if (user.Role.RoleName != "Contractor")
                {
                    Server.Transfer("NotAuthorized.aspx");
                }
            }
            if (!Page.IsPostBack)
            {
                LoadTimesheet();
            }
            else
            {
                _warningLabel.Text = "";
                _errorLabel.Text = "";
                _successLabel.Text = "";
            }
        }

        protected void FilterButton_Click(object sender, EventArgs e)
        {
            try
            {
                string statusname = _statusDropDownList.Text;
                Guid statusId = Guid.Parse(_timesheetstatusBusiness.GetStatusIdByStatusName(statusname).ToString());
                if (String.IsNullOrEmpty(_fromDateTextBox.Text) || String.IsNullOrEmpty(_toDateTextBox.Text))
                {
                    LoadTimesheet();
                }
                else if (Session["user"] != null)
                {
                    DateTime fromDate = DateTime.Parse(_fromDateTextBox.Text, CultureInfo.CurrentCulture);
                    DateTime toDate = DateTime.Parse(_toDateTextBox.Text, CultureInfo.CurrentCulture);
                    User user = (User)Session["user"];
                    _timesheetListView.DataSource = _timesheetBusiness.GetByFilterRange(user.UserName.ToString(), statusId, fromDate, toDate);
                    _timesheetListView.DataBind();
                }
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            FilterButton_Click(null, null);
            _timesheetListView.DataBind();
        }


        protected void TimesheetListView_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            try
            {
                //StatusLabel
                Label statusLabel = _timesheetListView.Items[e.NewEditIndex].FindControl("StatusLabel") as Label;
                if (statusLabel == null)
                {
                    e.Cancel = true;
                }
                if (statusLabel.Text == "Approved")
                {
                    _errorLabel.Text = "Timesheet was approved.";
                    _timesheetListView.EditIndex = -1;
                    e.Cancel = true;
                }
                else if (statusLabel.Text == "Rejected")
                {
                    _errorLabel.Text = "Timesheet was Rejected.";
                    _timesheetListView.EditIndex = -1;
                    e.Cancel = true;
                }
                else if (statusLabel.Text == "Pending")
                {
                    _timesheetListView.EditIndex = e.NewEditIndex;
                }
                LoadTimesheet();
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
        }

        protected void TimesheetListView_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            try
            {
                Label TimeSheetIdLable = null;
                TextBox TimeSheetDateTextBox = null;
                TextBox TitleTextBox = null;
                TextBox DescriptionTextBox = null;
                Control controlTimeSheetId = _timesheetListView.Items[e.ItemIndex].FindControl("TimesheetIdLabel");
                if (controlTimeSheetId != null)
                {
                    TimeSheetIdLable = (Label)controlTimeSheetId;
                }
                Control controlDateTime = _timesheetListView.Items[e.ItemIndex].FindControl("TimesheetTextBox");
                TimeSheetDateTextBox = new TextBox();
                if (controlDateTime != null)
                {
                    TimeSheetDateTextBox = (TextBox)controlDateTime;
                }
                Control controlWorkingTime = _timesheetListView.Items[e.ItemIndex].FindControl("WorkingTimeTextBox");
                TextBox WorkingTimeTextBox = new TextBox();
                if (controlWorkingTime != null)
                {
                    WorkingTimeTextBox = (TextBox)controlWorkingTime;
                }
                Control controlTitle = _timesheetListView.Items[e.ItemIndex].FindControl("TitleTextBox");
                TitleTextBox = new TextBox();
                if (controlTitle != null)
                {
                    TitleTextBox = (TextBox)controlTitle;
                }
                Control controlDescription = _timesheetListView.Items[e.ItemIndex].FindControl("DesTextBox");
                DescriptionTextBox = new TextBox();
                if (controlDescription != null)
                {
                    DescriptionTextBox = (TextBox)controlDescription;
                }
                MockDataTransferObject.Timesheet timeSheet = _timesheetBusiness.GetById(TimeSheetIdLable.Text);
                //get value form control update in database

                //assigns the value from control TextBox
                string timesheetDateInput = TimeSheetDateTextBox.Text;
                string workingTimeInput = WorkingTimeTextBox.Text;
                string titleInput = TitleTextBox.Text;
                string descriptionInput = DescriptionTextBox.Text;
                //check values on control is valid 
                DateTime timesheetDate = DateTime.Now;
                bool timesheetDateValid = DateTime.TryParse(timesheetDateInput, out timesheetDate);
                bool titleEmpty = String.IsNullOrEmpty(titleInput.Trim());
                bool descriptionEmpty = String.IsNullOrEmpty(descriptionInput.Trim());
                bool isValid = true;
                if (!timesheetDateValid)
                {
                    TimeSheetDateTextBox.CssClass = "inp-datetime-error";
                    TimeSheetDateTextBox.Attributes["title"] = "Timesheet date is invalid !";
                    isValid = false;
                }
                else if (!CheckDateTimeValid(timesheetDate))
                {
                    TimeSheetDateTextBox.CssClass = "inp-datetime-error";
                    TimeSheetDateTextBox.Attributes["title"] = "Timesheet date must in range from  " + timeSheet.Contract.StartDate.ToString("MM/dd/yyyy", CultureInfo.CurrentCulture) + "   to   " + timeSheet.Contract.EndDate.ToString("MM/dd/yyyy", CultureInfo.CurrentCulture);
                    isValid = false;
                }
                int workingTime = 0;
                bool workingTimeValid = Int32.TryParse(workingTimeInput, out workingTime);
                if (!workingTimeValid)
                {
                    WorkingTimeTextBox.Attributes["title"] = "Working time is invalid !";
                    WorkingTimeTextBox.CssClass = "inp-datetime-error";
                    isValid = false;
                }
                else if (!TimesheetBusiness.CheckWorkingTimeValid(workingTime))
                {
                    WorkingTimeTextBox.Attributes["title"] = "Working time must in range (1-23)";
                    WorkingTimeTextBox.CssClass = "inp-datetime-error";
                    isValid = false;
                }
                if (titleEmpty)
                {
                    TitleTextBox.Attributes["title"] = "Title is required";
                    TitleTextBox.CssClass = "inp-datetime-error";
                    isValid = false;
                }
                if (descriptionEmpty)
                {
                    DescriptionTextBox.Attributes["title"] = "Description is required";
                    DescriptionTextBox.CssClass = "inp-datetime-error";
                    isValid = false;
                }
                // get the values ​​to update
                timeSheet.TimesheetDate = timesheetDate;
                timeSheet.WorkingTime = workingTime;
                timeSheet.Title = titleInput;
                timeSheet.Description = descriptionInput;
                if (isValid)
                {
                    _timesheetBusiness.Update(timeSheet);
                    _timesheetListView.EditIndex = -1;
                    LoadTimesheet();
                }
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void TimesheetListView_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            try
            {
                Label timesheetIdLabel = (_timesheetListView.Items[e.ItemIndex].FindControl("TimeSheetIdLabel")) as Label;
                string timeSheetIdString = timesheetIdLabel.Text;
                Guid timesheetId = Guid.Parse(timeSheetIdString.ToString());
                _timesheetBusiness.Delete(timesheetId);
                _successLabel.Text = "Delete timesheet successfully!";
                LoadTimesheet();
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void TimesheetListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
        {
            _timesheetListView.EditIndex = -1;
            LoadTimesheet();
        }

        protected void StatusDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string statusname = _statusDropDownList.Text;
                Guid statusId = Guid.Parse(_timesheetstatusBusiness.GetStatusIdByStatusName(statusname).ToString());
                if (Session["user"] != null)
                {
                    User user = (User)Session["user"];
                    _timesheetListView.DataSource = _timesheetBusiness.GetByFilter(user.UserName, statusId);
                    _timesheetListView.DataBind();
                }
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }

        }

        protected void AllSearchCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (_allSearchCheckBox.Checked == true)
            {
                _statusDropDownList.AutoPostBack = false;
            }
            else
            {
                _statusDropDownList.AutoPostBack = true;
            }
        }

        protected void TimesheetListView_DataBound(object sender, EventArgs e)
        {
            if (_timesheetListView.EditIndex == -1)
            {
                foreach (ListViewDataItem item in _timesheetListView.Items)
                {
                    Label statusLabel = (Label)item.FindControl("StatusLabel");
                    Label TimeSheetIdLable = (Label)item.FindControl("TimesheetIdLabel");

                    Guid timesheetId = Guid.Parse(TimeSheetIdLable.Text.ToString());
                    object reason = _reasonBusiness.GetReasonByStatusName(timesheetId, statusLabel.Text);
                    if (statusLabel.Text == "Rejected")
                    {
                        Label labelResult = (Label)item.FindControl("ReasonLabel");
                        labelResult.Text = reason.ToString();
                    }
                    else
                    {
                        Label labelResult = (Label)item.FindControl("ReasonLabel");
                        labelResult.Text = "";
                    }
                }
            }
        }

        private void LoadTimesheet()
        {
            try
            {
                if (Session["user"] != null)
                {
                    User user = (User)Session["user"];
                    _statusDropDownList.DataSource = _timesheetstatusBusiness.RetrieveAllTimesheetStatus();
                    _statusDropDownList.DataMember = "StatusId";
                    _statusDropDownList.DataTextField = "StatusName";
                    _statusDropDownList.DataBind();
                    _timesheetListView.DataSource = _timesheetBusiness.GetByContractorUserName(user.UserName);
                    _timesheetListView.DataBind();
                }
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        private bool CheckDateTimeValid(DateTime dateTime)
        {
            User user = (User)Session["user"];
            object contractIdObject = _contractBusiness.GetContractIdByContractorUserId(user.UserId);
            Guid contractId = new Guid();
            if (contractIdObject != null && contractIdObject is Guid)
            {
                contractId = Guid.Parse(contractIdObject.ToString());
            }
            Contract contract = _contractBusiness.GetById(contractId);
            DateTime startDate = contract.StartDate;
            DateTime endDate = contract.EndDate;
            try
            {
                if (dateTime.CompareTo(startDate) > 0 && dateTime.CompareTo(endDate) < 0)
                {
                    return true;
                }
                return false;
            }
            catch (NullReferenceException)
            {
                return false;
            }
            catch (ArgumentNullException)
            {
                return false;
            }
            catch (FormatException)
            {
                return false;
            }
            catch (MockException)
            {
                return false;
            }
        }
    }
}